<template>
	<view class="pull_down_model" @touchstart="touchStart" @touchend="touchEnd" @touchmove="touchMove" :style="{
		'height':isDown?'calc( 100vh - 150rpx )':'unset',
		'overflow':isDown?'hidden':'unset'
	}">
		<view class="down" :style="{
			'height':downHeight + 'rpx'
		}">
		<view class="contain">
			{{frashTitle}}
		</view>
			
		</view>
		<view :style="{
			'transform':'translateY('+downHeight+'rpx)'
		}">
			<slot></slot>
		</view>
	</view>
</template>

<script>
	import {rpxToPx} from "@/common/utils/index.js"
	const windowWidth = getApp().globalData.sysWidth
	let startY = 0; //开始的y轴数值 
	let endY = 0; //结束的Y轴数值
	let currentY = 0; //移动的Y轴数值
	let frashFlag = false; //是否处于请求刷新态
	const time = null;
	export default{
		props:{
			// 滚动顶部距离
			scrollTop:{
				type:Number,
				default:()=>0
			}
		},
		data(){
			return{
				downHeight:0,
				isDown:false,
				frashTitle:"下拉刷新", 
				defaultH:80, //当拉到多少开始刷新
				
			}
		},
		methods:{
			// 刷新完毕
			frashOver(flag){
				if(flag){
					this.frashTitle = "刷新成功";
					time = setTimeout(()=>{
						this.downHeight = 0;
						this.isDown = false;
					},1500)
				}else{
					this.frashTitle = "刷新失败";
					time = setTimeout(()=>{
						this.downHeight = 0;
						this.isDown = false;
					},1500)
				}
				clearTimeout(time)
				time = null
			},
			touchStart(event){
				if(this.scrollTop === 0){
					const touch = event.touches[0] || event.changedTouches[0];
					// console.log('手指开始触摸',event);
					startY = touch.pageY
				}
			},
			touchEnd(event){
				if(this.scrollTop === 0){
					// console.log('手指移动结束',event)
					if(frashFlag){
						this.frashTitle = "正在刷新";
						this.downHeight = 40;
					}
				}
			},
			touchMove(event){
				if(this.scrollTop === 0){
					const touch = event.touches[0] || event.changedTouches[0];
					const moveY = touch.pageY;
					endY = moveY;
					currentY = endY - startY;
					if(currentY > 0){
						// console.log('手指下拉',currentY)
						this.isDown = true
						// this.downHeight = rpxToPx(currentY.toFixed(0),windowWidth)
						this.downHeight = currentY;
						if(currentY > this.defaultH){
							this.frashTitle = "释放刷新"
							frashFlag = true;
						}
					}
					// 判断是否在刷新态 取消刷新
					if(frashFlag){
						if(currentY<0 && currentY >= -40){
							this.downHeight = Math.abs(currentY) ;
						}
						if(currentY < -40){
							this.downHeight = 0;
							this.isDown = false;
							frashFlag = false
						}
					}
					// // console.log('手指触摸移动',val)
				}
			}
		}
	}
</script>

<style scoped lang="scss">
.pull_down_model{
	position: relative;
	.down{
		overflow: hidden;
		display: flex;
		align-items: center;
		justify-content: center;
		position: absolute;
		top: 0rpx;
		left: 0;
		width: 100%;
		color: #fff;
	}
}
</style>
